package com.smartcruise.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.WindowManager;

import com.smartcruise.util.ToastUtils;
import com.smartcruise.util.customView.LoadingDialog;

import io.realm.Realm;

/**
 * Created by FengChaoQun
 * on 2018/1/18 0018
 */

@SuppressLint("Registered")
public class BaseActivity extends AppCompatActivity implements BaseNormalView {

    private LoadingDialog loadingDialog;
    protected FragmentManager mFragmentManager;

    //手指上下滑动时的最小速度
    private static final int YSPEED_MIN = 1000;
    private static final int XSPEED_MIN = 200;
    //手指向上滑或下滑时的最小距离
    private static final int YDISTANCE_MIN = 100;
    //手指向右滑动时的最小距离
    private static int XDISTANCE_MIN = 150;
    protected boolean isEnableRightSlide = true;
    protected RightSlide rightSlide;
    //记录手指按下时的横坐标。
    private float xDown;
    //记录手指按下时的纵坐标。
    private float yDown;
    //记录手指移动时的横坐标。
    private float xMove;
    //记录手指移动时的纵坐标。
    private float yMove;
    //用于计算手指滑动的速度。
    private VelocityTracker mVelocityTracker;

    protected Realm realm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getXDISTANCE_MIN();
        setDefaultRightSlide();
        realm = Realm.getDefaultInstance();
        init();
    }

    private void getXDISTANCE_MIN() {
        try {
            WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics outMetrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(outMetrics);
            XDISTANCE_MIN = outMetrics.widthPixels / 10;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        realm.close();
        super.onDestroy();
    }

    private void init() {
        loadingDialog = new LoadingDialog(this);
        mFragmentManager = getSupportFragmentManager();
    }

    @Override
    public void showToast(CharSequence msg) {
        ToastUtils.showShort(getActivity(), msg);
    }

    @Override
    public void showToast(int msg) {
        ToastUtils.showShort(getActivity(), getString(msg));
    }

    /**
     * *describe:显示LoadingDialog
     */
    public void showLoadingDialog(String text) {
        //防止偶尔出现的的WindowManager$BadTokenException异常
        //先判断Activity是否被销毁 为确保 再加try catch
        if (this.isDestroyed()) {
            return;
        }
        try {
            loadingDialog.setLoadText(text);
            loadingDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void setLoadingDialogText(String text) {
        if (this.isDestroyed()) {
            return;
        }
        try {
            loadingDialog.setLoadText(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * *describe:关闭LoadingDialog
     */
    public void hideLoadingDialog() {
        loadingDialog.dismiss();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public BaseNormalView getBaseView() {
        return this;
    }

    @Override
    public Realm getRealm() {
        return realm;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        createVelocityTracker(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDown = event.getRawX();
                yDown = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                xMove = event.getRawX();
                yMove = event.getRawY();
                break;
            case MotionEvent.ACTION_UP:
                //滑动的距离
                int distanceX = (int) (xMove - xDown);
                int distanceY = (int) (yMove - yDown);
                //获取顺时速度
                int ySpeed = getYScrollVelocity();
                int xSpeed = getXScrollVelocity();
                //关闭Activity需满足以下条件：
                //1.x轴滑动的距离>XDISTANCE_MIN
                //2.y轴滑动的距离在YDISTANCE_MIN范围内
                //3.y轴上（即上下滑动的速度）<XSPEED_MIN，如果大于，则认为用户意图是在上下滑动而非左滑结束Activity
                if (distanceX > XDISTANCE_MIN && (distanceY < YDISTANCE_MIN && distanceY > -YDISTANCE_MIN)
                        && ySpeed < YSPEED_MIN && xSpeed > XSPEED_MIN) {
                    if (rightSlide != null) {
                        return rightSlide.rightSlide();
                    }
                }
                recycleVelocityTracker();
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 创建VelocityTracker对象，并将触摸界面的滑动事件加入到VelocityTracker当中。
     *
     * @param event
     */
    private void createVelocityTracker(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
    }

    /**
     * 回收VelocityTracker对象。
     */
    private void recycleVelocityTracker() {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
    }

    /**
     * @return 滑动速度，以每秒钟移动了多少像素值为单位。
     */
    private int getYScrollVelocity() {
        mVelocityTracker.computeCurrentVelocity(1000);
        int velocity = (int) mVelocityTracker.getYVelocity();
        return Math.abs(velocity);
    }

    private int getXScrollVelocity() {
        mVelocityTracker.computeCurrentVelocity(1000);
        int velocity = (int) mVelocityTracker.getXVelocity();
        return Math.abs(velocity);
    }

    public void setRightSlide(RightSlide rightSlide) {
        if (isEnableRightSlide) {
            this.rightSlide = rightSlide;
        }
    }

    /**
     * *describe:设置默认右滑关闭当前activity
     */
    public void setDefaultRightSlide() {
        setRightSlide(new RightSlide() {
            @Override
            public boolean rightSlide() {
                finish();
                return true;
            }
        });
    }

    public void clearRightSlide() {
        this.rightSlide = null;
    }

    public boolean isEnableRightSlide() {
        return isEnableRightSlide;
    }

    public void setEnableRightSlide(boolean enableRightSlide) {
        clearRightSlide();
        isEnableRightSlide = enableRightSlide;
    }

    @Override
    public void setOnLoadingDialogDismiss(LoadingDialog.onDismiss on) {
        loadingDialog.setOnDismiss(on);
    }

    public interface RightSlide {
        boolean rightSlide();
    }
}
